﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EventDispatcher
{
    /// <summary>
    /// 消息代理
    /// </summary>
    /// <param name="Netmsg"></param>
    public delegate void EventListenerDelegate(NetMessage Netmsg);

    private static EventDispatcher _instance;
    /// <summary>
    /// 事件分发单例
    /// </summary>
    public static EventDispatcher Instance
    {
        get
        {
            if (_instance == null)
                _instance = new EventDispatcher();
            return _instance;
        }
        private set
        {
            _instance = value;
        }
    }

    private Dictionary<uint, List<EventListenerDelegate>> eventListeners = new Dictionary<uint, List<EventListenerDelegate>>();
    /// <summary>
    /// 消息委托链
    /// </summary>
    public Dictionary<uint, List<EventListenerDelegate>> EventListeners
    {
        get
        {
            return eventListeners;
        }
        set
        {
            EventListeners = value;
        }
    }

    /// <summary>
    /// 注册事件
    /// </summary>
    /// <param name="eventType"></param>
    /// <param name="listener"></param>
    public void AddEventListener(uint eventType, EventListenerDelegate listener)
    {
        if (eventListeners.ContainsKey(eventType))
        {
            List<EventListenerDelegate> list = eventListeners[eventType];
            list.Add(listener);
        }
        else
        {
            List<EventListenerDelegate> list = new List<EventListenerDelegate>();
            list.Add(listener);
            eventListeners.Add(eventType, list);
        }
    }

    /// <summary>
    /// 移除事件
    /// </summary>
    /// <param name="eventType"></param>
    /// <param name="listener"></param>
    public void RemoveEventListener(uint eventType, EventListenerDelegate listener)
    {
        if (eventListeners.ContainsKey(eventType))
        {
            eventListeners[eventType].Remove(listener);
            if (eventListeners[eventType].Count == 0)
            {
                eventListeners.Remove(eventType);
            }
        }
    }

    /// <summary>
    /// 消息队列
    /// </summary>
    public Queue<NetMessage> queue = new Queue<NetMessage>();

    /// <summary>
    /// 添加消息
    /// </summary>
    /// <param name="msg"></param>
    public void AddMsg(NetMessage msg)
    {
        if (msg.Id == 0)
            return;
        queue.Enqueue(msg);
    }

    /// <summary>
    /// 删除消息
    /// </summary>
    public void Clear()
    {
        queue.Clear();
    }

    /// <summary>
    /// 分发消息
    /// </summary>
    /// <param name="msg"></param>
    public void ProcessMsg(NetMessage msg)
    {
        if (eventListeners.ContainsKey(msg.Id))
        {
            List<EventListenerDelegate> listeners = eventListeners[msg.Id];
            for (int i = 0; i < listeners.Count; i++)
            {
                listeners[i](msg);
            } 
        }
    }
}
